import dataSign from "@/utils/sign.js"
import store from "../store/index.js"

function back(url, message, redirectUrl = '/pages/Index/index') {
	store.commit('ChangeShowError', true);
	uni.showModal({
		title: '提示',
		content: message || '您尚未登录，是否前往登录',
		success: (res) => {
			if (res.confirm) {
				store.commit('ChangeOldUrl', url);
				store.commit('ChangeToken', '');
				store.commit('ChangeUserInfo', {})
				uni.navigateTo({
					url: '/pages/Login/index'
				});
				setTimeout(() => {
					store.commit('ChangeShowError', false);
				}, 3000)
			} else if (res.cancel) {
				store.commit('ChangeShowError', false);
				store.commit('ChangeOldUrl', '');
				let routes = getCurrentPages();
				if (routes.length > 1 && (routes[routes.length - 1] != routes[routes.length - 2])) {
					uni.navigateBack({
						delta: 1,
						fail: (err) => {
							uni.switchTab({
								url: '/pages/Index/index'
							});
						}
					});
				} else {
					uni.switchTab({
						url: '/pages/Index/index'
					});
				}
			}
		}
	});
}


function newBack(curRoute) {
	store.commit('ChangeShowError', true);
	uni.navigateTo({
		url: '/pages/Login/index?redirect=' + curRoute,
		animationType: 'slide-in-top',
		animationDuration: 300,
		success: () => {
			store.commit('ChangeShowError', false);
		},
		fail() {
			store.commit('ChangeShowError', false);
		}
	})
}

module.exports = (params) => {
	let url = params.url
	// let domain = 'http://116.62.239.98/'; //上线 服务端diyi
	let domain = 'https://v2.think-er.vip/'; //上线 服务端diyi
	// let domain = 'https://www.diyinft.net/'; //上线 服务端diyi
	let method = params.method;
	let pay = params.pay;
	let header = params.header || {};
	let data = params.data || {};
	let needToken = params.needToken || false
	let debug = params.debug || false
	//	请求方式 GET POST
	if (method) {
		method = method.toUpperCase(); //	小写转大写
		if (method == "POST") {
			header = {
				"content-type": "application/x-www-form-urlencoded"
			}
		}
	}
	//	发起请求 加载动画
	if (!params.hideLoading) {
		uni.showLoading({
			title: "",
			mask: true
		})
	}

	let token = uni.getStorageSync('token');
	//需要token的接口但是没有token
	// console.log('[是否TOKEN]',needToken,token)
	let routes = getCurrentPages();
	// console.log('[当前路由]',routes)
	let curRoute = routes[routes.length - 1].route
	let showError = uni.getStorageSync('showError') || false;
	let oldUrl = uni.getStorageSync('oldUrl');
	if (needToken && !token) {
		if (!showError) {
			// back(params.url)
			// console.log(params.url,curRoute);
			newBack(curRoute)
		} else if (oldUrl == params.url) {
			// back(params.url)
			newBack(curRoute)
		}
		return new Promise((resolve, reject) => {
			resolve({
				code: 12,
				msg: '请登录'
			})
		})
	}
	let sign = dataSign(data, domain, url)
	// console.log('当前-------------------------',sign)
	header = pay ? {} : {
		"content-type": "application/json;charset=UTF-8",
		"timestamp": sign.timestamp,
		"token": token,
		"debug": debug,
		"sign": sign.sign,
	}
	//	发起网络请求
	//console.log("header"+JSON.stringify(header))
	return new Promise((resolve, reject) => {
		uni.request({
			// url:domain+url,
			url: domain + url,
			method: method || "GET",
			header: header,
			data: data,
			dataType: "json",
			sslVerify: false, //	是否验证ssl证书
			success: res => {
				// console.log('服务端发送结果------------',res)
				if (res.statusCode != 200) {
					console.log('服务端发送结果------------', res)
					if (res.statusCode == 500) {
						uni.showToast({
							title: '请求超时',
							duration: 2000,
							icon: 'none'
						});
						return;
					} else if (res.statusCode == 404) {
						// uni.showToast({
						// 	title: '404-所请求的页面不存在',
						// 	duration: 2000,
						// 	icon:'none'
						// });
						return;
					} else if (res.data.code == 400 && res.data.msg == '请登录后操作') {
						if (!showError && token) {
							// back(params.url,'登录过期,请重新登录')
							newBack(curRoute)
						}
					} else if (res.data.code == 401) {
						if (!showError && token) {
							// back(params.url,'登录过期,请重新登录')
							newBack(curRoute)
						}
					}
					// uni.showToast({
					// 	title: res.data.msg || '未知错误'+res.statusCode,
					// 	duration: 2000,
					// 	icon:'none'
					// });
					return;
				}
				// if(res.data.code == 400){
				// 	uni.showToast({
				// 		title: res.data.msg,
				// 		duration: 2000,
				// 		icon:'none'
				// 	});
				// }
				if (res.data.code === 401) {
					if (!showError && !token) {
						// back(params.url,'登录过期,请重新登录')
						uni.navigateTo({
							url: '/pages/Login/index?redirect=' + curRoute,
							animationType: 'slide-in-bottom',
							animationDuration: 300
						})
					}
				}

				if (res.data.code == 403) {
					if (!showError && token) {
						// back(params.url,'登录过期,请重新登录')
						newBack(curRoute)
					}
				}
				// if(res.data.code==500){
				// 	uni.showToast({
				// 		title: res.data.msg,
				// 		duration: 2000,
				// 		icon:'none'
				// 	});						
				// }
				if (res.data.code == 201) {
					if (res.data.data.token) {
						token = res.data.data.token
					}
					let sign = dataSign({}, domain, 'v1/user')
					uni.request({
						url: domain + 'v1/user',
						method: "POST",
						header: {
							"content-type": "application/json;charset=UTF-8",
							"token": token,
							"timestamp": sign.timestamp,
							"debug": false,
							"sign": sign.sign
						},
						data: {},
						dataType: "json",
						sslVerify: false,
						success: res => {
							store.commit('ChangeUserInfo', res.data.data)
						},
					});
				}
				resolve(res.data || [])
			},
			fail: err => {
				if (err.errMsg == 'request:fail abort statusCode:-1 timeout') {
					uni.showToast({
						title: '连接超时,请检查您的网络设置',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				// uni.showToast({
				// 	title: err.msg || '网络链接中断',
				// 	duration: 2000,
				// 	icon:'none'
				// });
				resolve(err.data)
			},
			complete: (e) => {
				uni.hideLoading()
				uni.stopPullDownRefresh();
			}
		})
	})

}
